﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AG.Editor.Core.Data;
using System.Xml.Linq;

namespace AG.Editor.Core
{
    public class AGTextureFontStore
    {
        public void SaveTextureFont(AGEProject project, AGTextureFont textureFont)
        {
            string tfFileName = string.Format("{0}{1}.xml", project.GetFolderFonts(), textureFont.UniqueId);
            XDocument xDoc = new XDocument();

            XElement xFont = new XElement("font");
            xDoc.Add(xFont);

            xFont.Add(new XAttribute("unique-id", textureFont.UniqueId));
            xFont.Add(new XAttribute("id", textureFont.Id));
            xFont.Add(new XAttribute("caption", textureFont.Caption));
            xFont.Add(new XAttribute("texture", textureFont.TextureFile));

            for (int index = 0; index < textureFont.CharList.Count; index++)
            {
                AGTextureFontChar fc = textureFont.CharList[index];

                XElement xFontChar = new XElement("char");
                xFont.Add(xFontChar);

                xFontChar.Add(new XAttribute("name", fc.CharString));
                xFontChar.Add(new XAttribute("rect", string.Format("{0},{1},{2},{3}", fc.Left, fc.Top, fc.Left+ fc.Width, fc.Top + fc.Height)));
            }

            xDoc.Save(tfFileName);
        }

        public AGTextureFont LoadTextureFont(AGEProject project, AGTextureFontRef tfRef)
        {
            string tfFileName = string.Format("{0}{1}.xml", project.GetFolderFonts(), tfRef.TextureFontUniqueId);

            XDocument xDoc = XDocument.Load(tfFileName);
            XElement xFont = xDoc.Element("font");
            AGTextureFont tFont = new AGTextureFont(xFont.XGetAttrGuid("unique-id"));
            tFont.Id = xFont.XGetAttrInt("id");
            tFont.Caption = xFont.XGetAttrString("caption");
            tFont.TextureFile = xFont.XGetAttrString("texture");

            List<XElement> xCharList = xFont.XGetElements("char").ToList();
            for (int index = 0; index < xCharList.Count; index++)
            {
                XElement xChar = xCharList[index];
                AGTextureFontChar fontChar = new AGTextureFontChar();
                fontChar.CharString = xChar.XGetAttrString("name");
                string strRect = xChar.XGetAttrString("rect");
                string[] strRectArr = strRect.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                fontChar.Left = Convert.ToInt32(strRectArr[0]);
                fontChar.Top = Convert.ToInt32(strRectArr[1]);
                fontChar.Width = Convert.ToInt32(strRectArr[2]) - fontChar.Left;
                fontChar.Height = Convert.ToInt32(strRectArr[3]) - fontChar.Top;

                tFont.CharList.Add(fontChar);
            }

            return tFont;
        }
    }
}
